<?php
/**
 * 配置表模型
*/

namespace app\common\model;

use think\model\concern\SoftDelete;

class ShopConfig extends Model
{
    protected $name = 'shop_config';
    protected $autoWriteTimestamp = true;

    //可搜索字段
    protected $searchField = ['name',];

    /**
     * Desc: 设置配置值
     * @param $type
     * @param $name
     * @param $value
     */
    public static function set($type, $name, $value)
    {
    	$original = $value;
        $update_time = time();
        if (is_array($value)) {
            $value = json_encode($value, true);
        }
        $data = self::where(['type' => $type, 'name' => $name])
            ->find();
        if (empty($data)) {
            self::insert(['type' => $type, 'name' => $name, 'value' => $value]);
        } else {
            self::where(['type' => $type, 'name' => $name])
                ->update(['value' => $value, 'update_time' => $update_time]);
        }
        return $original;
    } 

    /**
     * Desc: 获取配置值
     * @param $type
     * @param $name
     * @param string $default_value
     * @return mixed|string
     */
    public static function get($type, $name = '',  $default_value = null)
    {
            $value = self::where(['type' => $type, 'name' => $name])->value('value');
            $json = json_decode($value, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $value = $json;
            }
            if ($value) {
                return $value;
            }
    }
}
